﻿using CodeGenerator.Dialog;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static CodeGenerator.Dialog.TemplateConfigDialog;

namespace CodeGenerator.Utils
{
    public class UpdateUtil
    {
        /// <summary>
        /// 版本比较
        /// </summary>
        /// <param name="version1">版本1</param>
        /// <param name="version2">版本2</param>
        /// <returns>版本1大于版本2时返回1，小于版本2时返回-1，相等时返回0</returns>
        /// <returns>版本1大于版本2时返回1，小于版本2时返回-1，相等时返回0</returns>
        public static int CampareVersion(string version1, string version2)
        {
            string[] v1Parts = version1.Split('.');
            string[] v2Parts = version2.Split('.');

            int maxLength = Math.Max(v1Parts.Length, v2Parts.Length);

            for (int i = 0; i < maxLength; i++)
            {
                int v1Part = i < v1Parts.Length ? int.Parse(v1Parts[i]) : 0;
                int v2Part = i < v2Parts.Length ? int.Parse(v2Parts[i]) : 0;

                if (v1Part > v2Part)
                {
                    return 1;
                }
                else if (v1Part < v2Part)
                {
                    return -1;
                }
            }
            return 0;

        }
        public static async Task<bool> CheckApplicationUpdateVersion(string url, bool showDialog = false, Action beforeShowDialog = null)
        {
            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage response = await client.GetAsync(url);

                if (!response.IsSuccessStatusCode)
                {
                    return false;
                }
                string responseBody = await response.Content.ReadAsStringAsync();
                var data = JsonConvert.DeserializeObject<List<AppUpdateInfo>>(responseBody);
                data.Sort((a, b) => b.Version.CompareTo(a.Version));
                if (data.Count > 0 && CampareVersion(data[0].Version, Main.Version) > 0)
                {
                    //有新版本
                    if (showDialog)
                    {
                        beforeShowDialog?.Invoke();
                        UpdateDialog dialog = new UpdateDialog(data);
                        dialog.StartPosition = FormStartPosition.CenterParent;
                        dialog.ShowDialog();
                    }
                }
                else
                {
                    return false;
                }
            }
            return true;
        }
        public static async Task<List<RemoteTemplate>> GetRemoteTemplates(string url)
        {
            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage response = await client.GetAsync(url);

                if (!response.IsSuccessStatusCode)
                {
                    return null;
                }
                string responseBody = await response.Content.ReadAsStringAsync();
                var data = JsonConvert.DeserializeObject<List<RemoteTemplate>>(responseBody);
                if (data.Count > 0)
                {
                    return data;
                }
            }
            return null;
        }
        public static void DownloadFile(string url, string savePath)
        {
            var directory = Path.GetDirectoryName(savePath);
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
            using (WebClient webClient = new WebClient())
            {
                webClient.DownloadFile(url, savePath);
            }
        }
    }
}
